<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>WebSocket 测试页面</title>
        <link rel="stylesheet" href="../styles/global.css" />
        <style>
            .container {
                max-width: 1200px;
                margin: 0 auto;
                padding: 20px;
            }

            .header {
                text-align: center;
                margin-bottom: 30px;
            }

            .status {
                display: inline-block;
                padding: 8px 16px;
                border-radius: 20px;
                font-weight: bold;
                margin-left: 10px;
            }

            .status.connected {
                background-color: #4caf50;
                color: white;
            }

            .status.disconnected {
                background-color: #f44336;
                color: white;
            }

            .status.connecting {
                background-color: #ff9800;
                color: white;
            }

            .controls {
                display: flex;
                gap: 10px;
                margin-bottom: 20px;
                flex-wrap: wrap;
            }

            .control-group {
                display: flex;
                flex-direction: column;
                gap: 5px;
            }

            .control-group label {
                font-weight: bold;
                font-size: 14px;
            }

            .control-group input,
            .control-group select {
                padding: 8px;
                border: 1px solid #ddd;
                border-radius: 4px;
                font-size: 14px;
            }

            .btn {
                padding: 10px 20px;
                border: none;
                border-radius: 4px;
                cursor: pointer;
                font-size: 14px;
                transition: background-color 0.3s;
            }

            .btn-primary {
                background-color: #2196f3;
                color: white;
            }

            .btn-primary:hover {
                background-color: #1976d2;
            }

            .btn-success {
                background-color: #4caf50;
                color: white;
            }

            .btn-success:hover {
                background-color: #45a049;
            }

            .btn-warning {
                background-color: #ff9800;
                color: white;
            }

            .btn-warning:hover {
                background-color: #f57c00;
            }

            .btn-danger {
                background-color: #f44336;
                color: white;
            }

            .btn-danger:hover {
                background-color: #d32f2f;
            }

            .messages {
                border: 1px solid #ddd;
                border-radius: 4px;
                height: 400px;
                overflow-y: auto;
                padding: 10px;
                background-color: #f9f9f9;
                margin-bottom: 20px;
            }

            .message {
                margin-bottom: 10px;
                padding: 8px;
                border-radius: 4px;
                border-left: 4px solid #2196f3;
                background-color: white;
            }

            .message.system {
                border-left-color: #4caf50;
                background-color: #e8f5e8;
            }

            .message.error {
                border-left-color: #f44336;
                background-color: #ffebee;
            }

            .message.broadcast {
                border-left-color: #ff9800;
                background-color: #fff3e0;
            }

            .message.private {
                border-left-color: #9c27b0;
                background-color: #f3e5f5;
            }

            .message-header {
                font-weight: bold;
                margin-bottom: 5px;
                color: #333;
            }

            .message-time {
                font-size: 12px;
                color: #666;
                float: right;
            }

            .message-content {
                margin-top: 5px;
                word-wrap: break-word;
            }

            .stats {
                display: grid;
                grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
                gap: 15px;
                margin-bottom: 20px;
            }

            .stat-card {
                background: white;
                border: 1px solid #ddd;
                border-radius: 8px;
                padding: 15px;
                text-align: center;
            }

            .stat-value {
                font-size: 24px;
                font-weight: bold;
                color: #2196f3;
                margin-bottom: 5px;
            }

            .stat-label {
                font-size: 14px;
                color: #666;
            }

            .clients-list {
                background: white;
                border: 1px solid #ddd;
                border-radius: 4px;
                padding: 15px;
                margin-bottom: 20px;
            }

            .client-item {
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 8px;
                border-bottom: 1px solid #eee;
            }

            .client-item:last-child {
                border-bottom: none;
            }

            .client-info {
                flex: 1;
            }

            .client-id {
                font-weight: bold;
                color: #333;
            }

            .client-details {
                font-size: 12px;
                color: #666;
                margin-top: 2px;
            }

            .client-actions {
                display: flex;
                gap: 5px;
            }

            .btn-small {
                padding: 4px 8px;
                font-size: 12px;
            }

            @media (max-width: 768px) {
                .controls {
                    flex-direction: column;
                }

                .control-group {
                    width: 100%;
                }

                .stats {
                    grid-template-columns: 1fr;
                }
            }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <h1>WebSocket 测试页面</h1>
                <div>
                    连接状态:
                    <span id="status" class="status disconnected">未连接</span>
                </div>
            </div>

            <div class="stats">
                <div class="stat-card">
                    <div class="stat-value" id="messageCount">0</div>
                    <div class="stat-label">消息数量</div>
                </div>
                <div class="stat-card">
                    <div class="stat-value" id="clientCount">0</div>
                    <div class="stat-label">在线客户端</div>
                </div>
                <div class="stat-card">
                    <div class="stat-value" id="uptime">00:00:00</div>
                    <div class="stat-label">运行时间</div>
                </div>
            </div>

            <div class="controls">
                <div class="control-group">
                    <label for="serverUrl">服务器地址:</label>
                    <input type="text" id="serverUrl" value="ws://localhost:18565/ws" placeholder="ws://localhost:18565/ws" />
                </div>
                <div class="control-group">
                    <button id="connectBtn" class="btn btn-success">连接</button>
                    <button id="disconnectBtn" class="btn btn-danger" disabled>断开</button>
                </div>
                <div class="control-group">
                    <label for="messageType">消息类型:</label>
                    <select id="messageType">
                        <option value="ping">心跳检测</option>
                        <option value="broadcast">广播消息</option>
                        <option value="private">私聊消息</option>
                        <option value="getClients">获取客户端列表</option>
                    </select>
                </div>
                <div class="control-group">
                    <label for="messageContent">消息内容:</label>
                    <input type="text" id="messageContent" placeholder="输入消息内容" />
                </div>
                <div class="control-group">
                    <label for="targetClient">目标客户端:</label>
                    <input type="text" id="targetClient" placeholder="客户端ID (私聊时使用)" />
                </div>
                <div class="control-group">
                    <button id="sendBtn" class="btn btn-primary" disabled>发送消息</button>
                    <button id="clearBtn" class="btn btn-warning">清空消息</button>
                </div>
            </div>

            <div class="clients-list">
                <h3>在线客户端</h3>
                <div id="clientsList">
                    <p style="text-align: center; color: #666">暂无客户端</p>
                </div>
            </div>

            <div class="messages" id="messages">
                <div class="message system">
                    <div class="message-header">系统消息</div>
                    <div class="message-time">刚刚</div>
                    <div class="message-content">WebSocket 测试页面已加载，请点击连接按钮开始测试。</div>
                </div>
            </div>
        </div>

        <script>
            class WebSocketTester {
                constructor() {
                    this.ws = null;
                    this.messageCount = 0;
                    this.startTime = Date.now();
                    this.uptimeInterval = null;

                    this.initElements();
                    this.bindEvents();
                    this.startUptime();
                }

                initElements() {
                    this.statusEl = document.getElementById('status');
                    this.messageCountEl = document.getElementById('messageCount');
                    this.clientCountEl = document.getElementById('clientCount');
                    this.uptimeEl = document.getElementById('uptime');
                    this.serverUrlEl = document.getElementById('serverUrl');
                    this.connectBtn = document.getElementById('connectBtn');
                    this.disconnectBtn = document.getElementById('disconnectBtn');
                    this.messageTypeEl = document.getElementById('messageType');
                    this.messageContentEl = document.getElementById('messageContent');
                    this.targetClientEl = document.getElementById('targetClient');
                    this.sendBtn = document.getElementById('sendBtn');
                    this.clearBtn = document.getElementById('clearBtn');
                    this.messagesEl = document.getElementById('messages');
                    this.clientsListEl = document.getElementById('clientsList');
                }

                bindEvents() {
                    this.connectBtn.addEventListener('click', () => this.connect());
                    this.disconnectBtn.addEventListener('click', () => this.disconnect());
                    this.sendBtn.addEventListener('click', () => this.sendMessage());
                    this.clearBtn.addEventListener('click', () => this.clearMessages());
                    this.messageTypeEl.addEventListener('change', () => this.updateSendButton());
                    this.messageContentEl.addEventListener('keypress', (e) => {
                        if (e.key === 'Enter') this.sendMessage();
                    });
                }

                connect() {
                    const url = this.serverUrlEl.value;
                    if (!url) {
                        this.addMessage('error', '请输入服务器地址');
                        return;
                    }

                    this.updateStatus('connecting', '连接中...');
                    this.connectBtn.disabled = true;

                    try {
                        this.ws = new WebSocket(url);

                        this.ws.onopen = () => {
                            this.updateStatus('connected', '已连接');
                            this.connectBtn.disabled = true;
                            this.disconnectBtn.disabled = false;
                            this.sendBtn.disabled = false;
                            this.addMessage('system', 'WebSocket 连接成功');
                            this.updateSendButton();
                        };

                        this.ws.onmessage = (event) => {
                            try {
                                const message = JSON.parse(event.data);
                                this.handleMessage(message);
                            } catch (error) {
                                this.addMessage('error', `消息解析错误: ${event.data}`);
                            }
                        };

                        this.ws.onclose = (event) => {
                            this.updateStatus('disconnected', '已断开');
                            this.connectBtn.disabled = false;
                            this.disconnectBtn.disabled = true;
                            this.sendBtn.disabled = true;
                            this.addMessage('system', `连接已断开 (代码: ${event.code})`);
                        };

                        this.ws.onerror = (error) => {
                            this.updateStatus('disconnected', '连接错误');
                            this.connectBtn.disabled = false;
                            this.disconnectBtn.disabled = true;
                            this.sendBtn.disabled = true;
                            this.addMessage('error', '连接发生错误');
                        };
                    } catch (error) {
                        this.updateStatus('disconnected', '连接失败');
                        this.connectBtn.disabled = false;
                        this.addMessage('error', `连接失败: ${error.message}`);
                    }
                }

                disconnect() {
                    if (this.ws) {
                        this.ws.close();
                        this.ws = null;
                    }
                }

                sendMessage() {
                    if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
                        this.addMessage('error', 'WebSocket 未连接');
                        return;
                    }

                    const type = this.messageTypeEl.value;
                    const content = this.messageContentEl.value;
                    const targetClient = this.targetClientEl.value;

                    let message = {type, data: content};

                    if (type === 'private' && targetClient) {
                        message.targetClientId = targetClient;
                    }

                    try {
                        this.ws.send(JSON.stringify(message));
                        this.addMessage('system', `发送消息: ${JSON.stringify(message)}`);
                        this.messageContentEl.value = '';
                    } catch (error) {
                        this.addMessage('error', `发送失败: ${error.message}`);
                    }
                }

                handleMessage(message) {
                    this.messageCount++;
                    this.messageCountEl.textContent = this.messageCount;

                    switch (message.type) {
                        case 'welcome':
                            this.addMessage('system', `欢迎消息: ${message.message} (客户端ID: ${message.clientId})`);
                            break;
                        case 'pong':
                            this.addMessage('system', '收到心跳响应');
                            break;
                        case 'broadcast':
                            this.addMessage('broadcast', `广播消息: ${JSON.stringify(message.data)}`);
                            break;
                        case 'private':
                            this.addMessage('private', `私聊消息 [${message.from}]: ${JSON.stringify(message.data)}`);
                            break;
                        case 'clients':
                            this.updateClientsList(message.data);
                            this.addMessage('system', `客户端列表更新: ${message.data.length} 个客户端`);
                            break;
                        case 'error':
                            this.addMessage('error', `错误: ${message.message}`);
                            break;
                        default:
                            this.addMessage('system', `收到消息: ${JSON.stringify(message)}`);
                    }
                }

                addMessage(type, content) {
                    const messageEl = document.createElement('div');
                    messageEl.className = `message ${type}`;

                    const headerEl = document.createElement('div');
                    headerEl.className = 'message-header';
                    headerEl.textContent = this.getMessageTypeName(type);

                    const timeEl = document.createElement('div');
                    timeEl.className = 'message-time';
                    timeEl.textContent = new Date().toLocaleTimeString();

                    const contentEl = document.createElement('div');
                    contentEl.className = 'message-content';
                    contentEl.textContent = content;

                    messageEl.appendChild(headerEl);
                    messageEl.appendChild(timeEl);
                    messageEl.appendChild(contentEl);

                    this.messagesEl.appendChild(messageEl);
                    this.messagesEl.scrollTop = this.messagesEl.scrollHeight;
                }

                getMessageTypeName(type) {
                    const names = {
                        system: '系统消息',
                        error: '错误消息',
                        broadcast: '广播消息',
                        private: '私聊消息',
                    };
                    return names[type] || '未知消息';
                }

                updateStatus(status, text) {
                    this.statusEl.className = `status ${status}`;
                    this.statusEl.textContent = text;
                }

                updateSendButton() {
                    const type = this.messageTypeEl.value;
                    const content = this.messageContentEl.value;
                    const targetClient = this.targetClientEl.value;

                    let canSend = content.trim() !== '';

                    if (type === 'private') {
                        canSend = canSend && targetClient.trim() !== '';
                    }

                    this.sendBtn.disabled = !canSend || !this.ws || this.ws.readyState !== WebSocket.OPEN;
                }

                clearMessages() {
                    this.messagesEl.innerHTML = '';
                    this.messageCount = 0;
                    this.messageCountEl.textContent = '0';
                }

                updateClientsList(clients) {
                    this.clientCountEl.textContent = clients.length;

                    if (clients.length === 0) {
                        this.clientsListEl.innerHTML = '<p style="text-align: center; color: #666;">暂无客户端</p>';
                        return;
                    }

                    this.clientsListEl.innerHTML = clients
                        .map(
                            (clientId) => `
                    <div class="client-item">
                        <div class="client-info">
                            <div class="client-id">${clientId}</div>
                            <div class="client-details">在线客户端</div>
                        </div>
                        <div class="client-actions">
                            <button class="btn btn-primary btn-small" onclick="tester.sendPrivateMessage('${clientId}')">私聊</button>
                        </div>
                    </div>
                `
                        )
                        .join('');
                }

                sendPrivateMessage(clientId) {
                    this.messageTypeEl.value = 'private';
                    this.targetClientEl.value = clientId;
                    this.updateSendButton();
                }

                startUptime() {
                    this.uptimeInterval = setInterval(() => {
                        const now = Date.now();
                        const uptime = now - this.startTime;
                        const hours = Math.floor(uptime / 3600000);
                        const minutes = Math.floor((uptime % 3600000) / 60000);
                        const seconds = Math.floor((uptime % 60000) / 1000);
                        this.uptimeEl.textContent = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
                    }, 1000);
                }
            }

            // 初始化测试器
            const tester = new WebSocketTester();
        </script>
    </body>
</html>
